import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QLabel
from PyQt6.QtCore import Qt

class DynamicWindowDemo(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("动态窗口示例")
        self.resize(400, 300)
        
        central_widget = QWidget()
        layout = QVBoxLayout()
        
        self.windows = []  # 保存窗口引用
        
        create_btn = QPushButton("创建新窗口")
        create_btn.clicked.connect(self.create_new_window)
        
        close_all_btn = QPushButton("关闭所有窗口")
        close_all_btn.clicked.connect(self.close_all_windows)
        
        layout.addWidget(create_btn)
        layout.addWidget(close_all_btn)
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)
    
    def create_new_window(self):
        window = QMainWindow(self)  # 设置主窗口为父窗口
        window.setWindowTitle(f"窗口 {len(self.windows) + 1}")
        window.resize(300, 200)
        
        label = QLabel(f"这是第 {len(self.windows) + 1} 个窗口")
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        window.setCentralWidget(label)
        window.show()
        self.windows.append(window)  # 保存引用
    
    def close_all_windows(self):
        for window in self.windows:
            window.close()
        self.windows = []

app = QApplication(sys.argv)
window = DynamicWindowDemo()
window.show()
sys.exit(app.exec())